import type { PayloadAction } from "@reduxjs/toolkit";
import {
  registerMicroApps,
  start,
  initGlobalState,
  MicroAppStateActions,
} from "qiankun";
import { appDefaultConfig } from "@config/appConfig";
import { createAppSlice } from "@model/utils";
import { RootState } from "@model/store";
export interface MicroSliceState {
  appConfig: any;
  values: {appValue: string | number | undefined};
}

const initialState: MicroSliceState = {
  appConfig: [],
  values: { appValue: 999 },
};

const actions: MicroAppStateActions = initGlobalState({ appValue: 10 });
export const microSlice = createAppSlice({
  name: "microStore",
  initialState,
  reducers: (create) => ({
    appRegister: create.reducer((state, action: any) => {
      registerMicroApps(appDefaultConfig);
      start();
    }),
    onGlobalStateChange: create.reducer((state, action: any) => {
      actions.onGlobalStateChange((state, prev) => {
        // state: 变更后的状态; prev 变更前的状态
        console.log(state, prev);
      });
    }),
    setGlobalState: create.reducer((state, action: any) => {
      actions.setGlobalState(state.values);
    }),
    offGlobalStateChange: create.reducer((state, action: any) => {
      actions.offGlobalStateChange();
    }),
  }),
  selectors: {},
});
export const {
  appRegister,
  onGlobalStateChange,
  setGlobalState,
  offGlobalStateChange,
} = microSlice.actions;
export const values = (state: RootState) => {
  return state.microStore.values;
};
// export const isHeaderMenu = (state: RootState) => {
//   return state.microStore.mainHeaderMenu;
// };
